package com.ljsw.util;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.renderscript.Sampler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.hdhe.uhf.reader.CaseString;
import com.bumptech.glide.disklrucache.DiskLruCache;
import com.ljsw.activity.R;
import com.ljsw.application.App;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.SuccessDialog;
import com.ljsw.entity.OperateLog;
import com.ljsw.fragment.KssmFragment;
import com.ljsw.server.UpServer;
import com.poka.device.RFIDDevice;
import com.poka.entity.ReciveList;
import com.poka_global_constant.GlobalConstant;
import com.poka_global_constant.Util;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.poka.device.LOCKDevice;


/**
 * 操作密码锁的工具类
 *
 * @author liancha
 */
public class DecodeLock implements OnClickListener {

    private static final String TAG = "DecodeLock";
    private Context context;
    private View view;
    public RadioGroup rg_zzx_num;    //周转箱编号单选组
    private Button btn_lock_zzx;    // 闭锁
    private Button btn_unLock_zzx;    //开锁
    private List<String> list; // 周转箱编号
    private Map<String, String> lockStateMap;    // 每个锁的状态， 周装箱编号：lock/unlock
    private List<String> locknum = new ArrayList<String>();//存储穿服务器的锁 号
    private Map<String, String> locknumMap = new HashMap<String, String>();
    private Map<String, String> locknumMapstateb = new HashMap<String, String>();
    private String selectedZzxNum;    // 点击单选按钮所选中的周转箱编号
    private String selectedLabelNum;    // 点击单选按钮所选中的周转箱编号 所对应的24位标签数字
    private ProgressDialog progressDialog;
    private LOCKDevice lockDevice;    // 密码锁实例

    public boolean isUsed = true; // 是否使用密码锁，true：使用， false：不使用
    public ArrayList newarraylist = new ArrayList();
    public static final int USE_DECODE_LOCK_OR_NO = 0;    // 是否使用密码锁
    public static final int OPERATE_LOCK = 1;    // 执行闭锁操作
    public static final int OPERATE_UNLOCK = 2;    // 执行开锁操作
    private String selenumber;
    private String Locknumtest;
    private LoginDialog lockdialog;//  开关锁dialog
    /**
     * Id to identity READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{"foo@example.com:hello", "bar@example.com:world"};
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */

    private RFIDDevice rfidDevice;
    private ReciveList receivelist;


    private final int OPEN_LOCK = 1;
    private final int CLOSE_LOCK = 0;

    private RFIDDevice.OnDataReceiveListener listener = null;
    private String operator = null;
    private List<String> Zlist = new ArrayList<String>();
    private ListView mlocklist;
    private Button mSearchLock;
    private Button mOpenLock;
    private Button mCloseLock;
    private TextView selectedItem;
    RadioButton rb;
    private TextView startsaomiao;

    private String zzxt;
    private boolean lockstate = false;
    private String lockstatenow;

    boolean Lockstatenow = false;
    String strBox = null;

    int o = 0;

    byte[] reply;
    byte[] tempbuffer = null;

    private Long LastClickTime;//最后一次点击时间
    Message msgaddelement;
    private LoginDialog dialog;//显示开关锁的状态
    private DialogManager dmanager;// 弹出框管理类
    private SuccessDialog successDialog;// 成功弹出框
    private TextView zzx_queren;
    public Handler handlerzhuan = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String result = null;
            switch (msg.what) {
                case 999: // 显示扫描的结果  kssfragment
                    Zlist.clear();
                    notifyZzxNumListChange();
                    zzxt = (String) msg.obj;
                    strBox = Guolv(zzxt);
                    Log.e("", "-----handler收到" + zzxt + Zlist.size());
                    if ("箱子规格不正确".equals(strBox)) {
                        showBigToast("请重试箱子格式不正确",100);
                    } else {
                        if ("箱子规格不正确".equals(strBox) && Zlist.contains(strBox) && strBox.contains("箱子规格不正确")) {
                            Log.e(TAG, "箱子规格不正确");
                        } else if (!"箱子规格不正确".equals(strBox) && !strBox.equals("") && !strBox.contains("箱子规格不正确")) {
                            Log.e(TAG, "strbox" + strBox);
                            com.android.hdhe.uhf.main.Util.play(1, 0);
                            Zlist.add(strBox);//添加过滤的箱子
                            locknumMap.put(zzxt, strBox);//锁号和箱子号
                        }
                    }

                    notifyZzxNumListChange();
                    break;
                case 996: // 显示扫描的结果 kssfragment  冲扫时传过来的可以注掉
//                    Zlist.clear();
//                    zzxt = (String) msg.obj;
//                    strBox = Guolv(zzxt);
//                    Log.e("", "-----handler收到" + zzxt + Zlist.size());
//                    if ("箱子规格不正确".equals(strBox)) {
//                    } else {
//                        if ("箱子规格不正确".equals(strBox) && Zlist.contains(strBox) && strBox.contains("箱子规格不正确")) {
//                            Log.e(TAG, "箱子规格不正确");
//                        } else if (!"箱子规格不正确".equals(strBox) && !strBox.equals("") && !strBox.contains("箱子规格不正确")) {
//                            Log.e(TAG, "strbox" + strBox + Zlist.size());
//                            com.android.hdhe.uhf.main.Util.play(1, 0);
//                            Zlist.add(strBox);//添加过滤的箱子
//                        }
//                    }
//                    notifyZzxNumListChange();
                    break;
                case 992: // 显示扫描的结果 kugnafragment  传过来的值
                    zzxt = (String) msg.obj;
                    strBox = Guolv(zzxt);
                    Log.e("", "-----handler收到" + zzxt + Zlist.size());
                    if ("箱子规格不正确".equals(strBox)) {

                    } else {
                        if ("箱子规格不正确".equals(strBox) && strBox.contains("箱子规格不正确")) {
                            Log.e(TAG, "箱子规格不正确");
                        } else if (!"箱子规格不正确".equals(strBox) && !strBox.equals("") && !strBox.contains("箱子规格不正确") && !Zlist.contains(strBox)) {
                            Log.e(TAG, "strbox   " + strBox);
                            Zlist.add(strBox);//添加过滤的箱子
                            locknumMap.put(zzxt, strBox);//锁号和箱子号;//锁号和箱子号
                        }
                    }
                    notifyZzxNumListChange();
                    break;

            }
        }
    };

    /***
     * 传输选中的箱号
     */
    public Handler getHandler() {

        return handlerzhuan;
    }

    @SuppressLint("HandlerLeak")

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String result = null;
            switch (msg.what) {

                case USE_DECODE_LOCK_OR_NO:
                    Log.e(TAG, "msg.obj====" + msg.obj);
                    initCodedLock();//初始化密码锁

                    btn_lock_zzx.setVisibility(View.VISIBLE);
                    btn_unLock_zzx.setVisibility(View.VISIBLE);
                    //当成功完成上锁 后按钮消失（隐藏）
                    break;
                case OPERATE_LOCK:
                    btn_unLock_zzx.setEnabled(true);
                    btn_lock_zzx.setEnabled(true);
                    progressDialog.dismiss();
                    result = msg.obj.toString();
                    saveOperateDecodedLockLog("对周转箱：" + strBox + "，执行闭锁操作，操作结果是：" + result);
                    showBigToast("" + result, Toast.LENGTH_SHORT);
                    changeLockState(result);

                    break;
                case OPERATE_UNLOCK:
                    btn_unLock_zzx.setEnabled(true);
                    btn_lock_zzx.setEnabled(true);
                    progressDialog.dismiss();
                    result = msg.obj.toString();
                    saveOperateDecodedLockLog("对周转箱：" + strBox + "，执行开锁操作，操作结果是：" + result);
                    showBigToast(" " + result, Toast.LENGTH_SHORT);
                    changeLockState(result);
                    break;

                default:
                    break;
            }
        }

        ;
    };


    public DecodeLock(Context context, final View view, RadioGroup rg_zzx_num, Button btn_lock_zzx,
                      Button btn_unLock_zzx, List<String> listtest, TextView zzx_queren) {
        this.context = context;
        this.view = view;
        this.rg_zzx_num = rg_zzx_num;
        this.btn_lock_zzx = btn_lock_zzx; //上锁
        this.btn_unLock_zzx = btn_unLock_zzx;//开锁
        this.lockStateMap = new HashMap<String, String>();
        this.progressDialog = new ProgressDialog(context);
        this.progressDialog.setCancelable(false);
        this.zzx_queren = zzx_queren;
        /**
         * 为密码锁按钮添加监听事件
         */

        this.btn_lock_zzx.setOnClickListener(this);
        this.btn_unLock_zzx.setOnClickListener(this);
        this.rg_zzx_num.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) view.findViewById(checkedId);

                selectedZzxNum = radioButton.getText().toString();//箱子号

                selectedLabelNum = "" + (int) selectedZzxNum.charAt(0)
                        + (int) selectedZzxNum.charAt(1)
                        + selectedZzxNum.substring(2, 8)
                        + (int) selectedZzxNum.charAt(8)
                        + (int) selectedZzxNum.charAt(9)
                        + "0000000000";
                Log.e(TAG, "锁好的值" + selectedLabelNum + "!!!!!" + selectedZzxNum);
            }

        });
        operator = "user";
        this.useCodedLockOrNo();
        receivelist = new ReciveList();
        dmanager = new DialogManager(context);
        lockdialog = dmanager.getLoginDialog();
    }

    private boolean isfastDoubleClick() {
        Long time = System.currentTimeMillis();
        Long timeDouble = time - LastClickTime;
        Log.i(TAG, "lsn timeDouble = " + timeDouble);
        if (0 < timeDouble && timeDouble < 600) {
            return true;
        }
        LastClickTime = time;
        return false;
    }

//    public void searchItemLock() {
//        new Thread() {
//            public void run() {
//                receivelist = new ReciveList();
//                rfidDevice = RFIDDevice.getInstance();//new对象
//
//                searchLock();
//            }
//
//            ;
//        }.start();
//
//    }

    @Override
    public void onClick(View v) {
        rfidDevice = RFIDDevice.getInstance();//new对象

        switch (v.getId()) {
            case R.id.btn_unLock_zzx:    // 打开密码锁
                LastClickTime = System.currentTimeMillis();
                if (isfastDoubleClick()) {
                    return;
                }
                btn_unLock_zzx.setEnabled(false);
                btn_lock_zzx.setEnabled(false);
                lockstatenow = "开锁";
                Log.e(TAG, "btn_unLock_zzxtest==========" + lockstatenow);
                searchLock();

                btn_unLock_zzx.setText("开锁");
                btn_unLock_zzx.setEnabled(true);
                this.progressDialog.dismiss();

                break;
            case R.id.btn_lock_zzx://关闭锁的号码
                btn_unLock_zzx.setEnabled(false);
                btn_lock_zzx.setEnabled(false);
                LastClickTime = System.currentTimeMillis();
                if (isfastDoubleClick()) {
//                    return;
                }
                btn_lock_zzx.setEnabled(true);
                lockstatenow = "关锁";

                this.progressDialog.setTitle("正在关闭密码锁");
                this.progressDialog.show();
                this.progressDialog.setTitle("正在关闭密码锁");

                searchLock();
                btn_lock_zzx.setText("闭锁");
                btn_lock_zzx.setEnabled(true);
                this.progressDialog.dismiss();
                break;
            default:
                Log.e(TAG, "什么也不做");
                showBigToast("什么也不做", 100);
                break;
        }

    }

    /**
     * 访问服务端确定是否使用密码锁
     */
    private void useCodedLockOrNo() {
        new Thread() {
            public void run() {
                try {
                    boolean useCodedLock = UpServer.isUseCodedLock(null);
                    Log.e(TAG, "useCodedLock" + useCodedLock);
                    Message msg = handler.obtainMessage();
                    msg.obj = useCodedLock;
                    msg.what = DecodeLock.USE_DECODE_LOCK_OR_NO;
                    Log.e(TAG, "msg===" + msg);
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();
    }

    /**
     * 初始化密码锁
     */
    private void initCodedLock() {
        new Thread() {
            public void run() {
                lockDevice = LOCKDevice.getInstance();
            }

            ;
        }.start();
    }

    /**
     * 扫描周转箱之后更新扫描到的结果,显示在屏幕上
     */
    public void notifyZzxNumListChange() {
        this.rg_zzx_num.removeAllViews();
        this.selectedLabelNum = null;
        this.selectedZzxNum = null;
        if (this.Zlist != null && Zlist.size() > 0) {
            for (String num : Zlist) {
                rb = new RadioButton(context);//RadioButton 动态添加list集合数据
                Log.e(TAG, "num" + num);
                rb.setText(num);
                rb.setTextColor(Color.rgb(0, 0, 0));
                Log.e(TAG, "rb=====" + rb + Zlist.size());
                this.rg_zzx_num.addView(rb);

            }
        }
    }

    /*
     * 获取rudiobutoon
     * 获取锁号selectedLabelNum
     * 和周转箱子号selectedZzxNum
     * @return
     */
    public String Lockitem() {
        this.rg_zzx_num.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) view.findViewById(checkedId);

                selectedZzxNum = radioButton.getText().toString();//箱子号
                selectedLabelNum = "" + (int) selectedZzxNum.charAt(0)
                        + (int) selectedZzxNum.charAt(1)
                        + selectedZzxNum.substring(2, 8)
                        + (int) selectedZzxNum.charAt(8)
                        + (int) selectedZzxNum.charAt(9)
                        + "0000000000";
                Log.e(TAG, "锁好的值" + selectedLabelNum + "!!!!!" + selectedZzxNum);
            }

        });

        return selectedZzxNum;
    }

    /**
     * 查找周围的电子锁并接收有效字节数据
     */
    public void searchLock() {
        int locknum = 0;
        int count = 0;
        boolean isfinished = true;
        List<String> rfidSerialID = new ArrayList();
        String selectItem = "";
        int cn = 0;

        try {
            receivelist.removeAllElement();    //清空有效字节数组长度
            createListener();//接收有效字节并实心抽象实现方法需要先覆盖发出发接收方法
            rfidDevice.unSelectMode();//取消选中锁号
            Thread.sleep(2000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        rfidDevice.searchEPC();//发送消息命令

        int replynum = receivelist.getElementNum();//接收返回有效字节数组
        ArrayList<String> LockID = new ArrayList<String>();//c存放锁号码
        if (!TextUtils.isEmpty(selectedLabelNum)||selectedLabelNum!=null) {
            LockID.add(selectedLabelNum);
            Log.e(TAG, "selectedLabelNum=======" + selectedLabelNum);
            Log.e(TAG, "跳出啊222222" + zzxt);
            for (int i = 0; i < replynum; i++) {
                Log.e(TAG, "跳出啊" + zzxt);
                reply = receivelist.getFinishElement();
                String replyString = com.poka_global_constant.Util.byte2HexStr(reply);
                if (!replyString.equals("BB01FF000115167E") && replyString.length() > 40) {
                    Log.e(TAG, "rg_zzx_num" + rg_zzx_num.toString());
                    Log.e(TAG, "zzxt=" + zzxt + "replyString.substring=" + replyString.substring(16, 40) + "selectedZzxNum=" + selectedZzxNum);

                }
            }

            Log.e(TAG, "zzxt！！！！" + LockID.size());
            for (int i = 0; i < LockID.size(); i++) {
                rfidDevice.unSelectMode();
                rfidDevice.selectMode();
                reply = receivelist.getFinishElement();

                do {
                    rfidDevice.selectEPC(LockID.get(i));//循环查询锁号//改
                    Log.e(TAG, "searchLock锁的号码！！！！" + LockID.get(i));
                    replynum = receivelist.getElementNum();
                    count++;
                } while (replynum == 0 && count < GlobalConstant.TRY_TICK);//TRY_TICK = 20;
                Locknumtest = LockID.get(i);//查找集合条目的上一把锁号码
                Log.e(TAG, "searchLock循环赋值Locknumtest" + Locknumtest);
                if (count == GlobalConstant.TRY_TICK) {
                    continue;
                }
                reply = receivelist.getFinishElement();
                String replyString = Util.byte2HexStr(reply);

                // 获取锁的信息
                count = 0;
                do {
                    rfidDevice.LockOperation(1, null);
                    replynum = receivelist.getElementNum();
                    reply = receivelist.getFinishElement();
                    count++;
                    if (count == GlobalConstant.TRY_TICK)
                        break;
                }
                while (!(reply.length > 21 && reply[2] == 0x49 && reply[20] == 0x00));
                if (count == GlobalConstant.TRY_TICK) {
                    continue;
                }

                count = 0;
                do {
                    rfidDevice.readUserData(0, 48);
                    reply = receivelist.getFinishElement();
                    count++;
                    if (count == GlobalConstant.TRY_TICK)
                        break;
                } while (!(reply.length > 3 && reply[2] == 0x39));
                if (count < GlobalConstant.TRY_TICK) {//判断 count是否小于20
                    replyString = rfidDevice.getResult(reply);
                    String result = replyString.substring(8, 10);
                    if (result.equals("00")) {//锁判断是否上电
                        rfidSerialID.add(LockID.get(i));
                        Log.e(TAG, "锁没上电result" + result);
                        locknum++;
                        if (locknum > 0) {
                            Log.e(TAG, "locknum==赋值>0" + locknum);
                            selenumber = LockID.get(i);
                            rfidSerialID.add(LockID.get(i));
                            locknum++;
                            if (lockstatenow.equals("开锁")) {
                                try {
                                    manageLock(OPEN_LOCK);
                                    cn = cn + 1;
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.e(TAG, "search！！！！！开" + lockstatenow + "异常信息" + e);
                                    manageLock(OPEN_LOCK);
                                }
                                Log.e(TAG, "search！！！！！开" + lockstatenow);
                                return;
                            } else if (lockstatenow.equals("关锁")) {
                                btn_lock_zzx.setText("正在处理********");
                                cn = cn + 1;
                                manageLock(CLOSE_LOCK);
                                this.progressDialog.setTitle("正在关闭密码锁");
                                Log.e(TAG, "search！！！！！关" + lockstatenow);

                                return;
                            } else {
                                Log.e(TAG, "不做操作" + lockstatenow);
                                return;
                            }
                        }
                    } else {
                        if (locknum == 0) {
                            showBigToast("请检查电源", 300);
                            Log.e(TAG, "search不做操作");
                            locknum++;

                        }
                    }
                }
            }



        } else if (TextUtils.isEmpty(selectedLabelNum) || selectedLabelNum == ""||selectedLabelNum.equals("")) {
            showBigToast("请选择锁", 100);
            Log.e(TAG, "search====" + zzxt);
            btn_unLock_zzx.setEnabled(true);
            btn_lock_zzx.setEnabled(true);
            return ;


        }

        Log.e(TAG, "跳出啊" + zzxt);


        rfidDevice.unSelectMode();
        if (locknum >= 0) {
            locknum = locknum + 1;
            Log.e(TAG, "search未找到上电的锁" + selenumber);
            showBigToast("未找到上电的锁请对准箱子电池位置", 300);
            if (locknum >= 3) {
                oPenClose();
            }
            btn_unLock_zzx.setEnabled(true);
            btn_lock_zzx.setEnabled(true);
            return;

        }


    }

//    private void closeLock() {
//        this.progressDialog.setTitle("正在关闭密码锁");
//        manageLock(CLOSE_LOCK);
//        Log.e(TAG, "执行关锁操作!!!!!!!!!!!!");
//        return;
//    }
//    private void openLock() {
//        this.progressDialog.setTitle("正在关闭密码锁");
//        manageLock(OPEN_LOCK);
//        Log.e(TAG, "执行关锁操作!!!!!!!!!!!!");
//        return;
//    }


    /**
     * 执行开关锁的操作
     *
     * @param op
     */
    private void manageLock(int op) {
        Log.e(TAG, "manageLock" + "op的值" + op);
        int count = 0;
        int replynum = 0;
        String replyString = "";
        String result = null;
        String lockerstatus = null;
        String linkerstatus = null;
        String initialstatus = null;
        String random = null;
        manageButton(false);
        int testcount = 0;
        testcount = testcount + 1;
        receivelist.removeAllElement();
        byte[] cmd = op == 1 ? Util.hexStr2Bytes("0100") : Util.hexStr2Bytes("0200");
        byte[] reply = null;
        rfidDevice.selectMode();
        reply = receivelist.getFinishElement();
        count = 0;
        do {
            rfidDevice.selectEPC(selenumber);
            replynum = receivelist.getElementNum();
            count++;
        } while (replynum == 0 && count < GlobalConstant.TRY_TICK);

        if (count == GlobalConstant.TRY_TICK) {

            showBigToast("没找到上电的锁请对准箱子电池位置", 100);
            btn_unLock_zzx.setEnabled(true);
            btn_lock_zzx.setEnabled(true);
            Log.e(TAG, "无法选择对应的锁!!!!!!!");
            return;
        }
        reply = receivelist.getFinishElement();
        replyString = Util.byte2HexStr(reply);
        // 获取锁的信息
        count = 0;
        do {
            rfidDevice.LockOperation(1, null);
            replynum = receivelist.getElementNum();
            reply = receivelist.getFinishElement();
            Log.e(TAG, "Locknumtest===" + selenumber);
            Log.e(TAG, "reply===" + reply);
            count++;
            if (count == GlobalConstant.TRY_TICK)
                break;
        } while (!(reply.length > 21 && reply[2] == 0x49 && reply[20] == 0x00));
        if (count == GlobalConstant.TRY_TICK) {
            btn_unLock_zzx.setEnabled(true);
            btn_lock_zzx.setEnabled(true);
            showBigToast("锁接收信息异常请重试", 100);
            btn_unLock_zzx.setEnabled(true);
            btn_lock_zzx.setEnabled(true);
            Log.e(TAG, "发送指令失败!!!!!!!!!!!!" + count);
            return;
        }
        count = 0;
        do {
            rfidDevice.readUserData(0, 48);
            reply = receivelist.getFinishElement();
            count++;
            if (count == GlobalConstant.TRY_TICK)
                break;
        } while (!(reply.length > 3 && reply[2] == 0x39));
        if (count < GlobalConstant.TRY_TICK) {
            replyString = rfidDevice.getResult(reply);
            result = replyString.substring(8, 10);
            lockerstatus = replyString.substring(34, 36);
            linkerstatus = replyString.substring(36, 38);
            initialstatus = replyString.substring(38, 40);
            random = replyString.substring(40, 72);
            if (!(linkerstatus.equals("00") || linkerstatus.equals("01") || linkerstatus.equals("FF"))) {
                showBigToast("请检查箱是否盖好", 300);
                Log.e(TAG, "链状态查询异常!!!!!!!!!!!!" + linkerstatus);//7F 127
                btn_unLock_zzx.setEnabled(true);
                btn_lock_zzx.setEnabled(true);
                return;
            }
            if (!(initialstatus.equals("00") || initialstatus.equals("01"))) {
                Log.e(TAG, "初始化查询异常!!!!!!!!!!!!" + initialstatus);
                showBigToast("未查到锁请对准电池位置并重试", 100);
                btn_unLock_zzx.setEnabled(true);
                btn_lock_zzx.setEnabled(true);
                return;
            }
            if (!(lockerstatus.equals("00") || lockerstatus.equals("01") || lockerstatus.equals("FF"))) {
                showBigToast("请对准电池位置", 100);
                btn_unLock_zzx.setEnabled(true);
                btn_lock_zzx.setEnabled(true);
                Log.e(TAG, "锁舌查询异常!!!!!!!!!!!!" + lockerstatus);
                return;
            }
            o = o + 1;
            Log.e(TAG, "测试mangerlock  走几次" + o);
            if (result.equals("00")) {
                if (linkerstatus.equals("01") || linkerstatus.equals("FF")) {
                    Log.e(TAG, "获取锁状态失败!!!!!!!!!!!!");
                    showBigToast(linkerstatus.equals("01") ? "拉链不就位" : "拉链状态异常", Toast.LENGTH_SHORT);
                    btn_unLock_zzx.setEnabled(true);
                    btn_lock_zzx.setEnabled(true);
                    return;
                }
                if (initialstatus.equals("01")) {
                    showBigToast("锁具未初始化请重试", Toast.LENGTH_SHORT);
                    Log.e(TAG, "获取锁状态失败!!!!!!!!!!!!" + initialstatus);
                    btn_unLock_zzx.setEnabled(true);
                    btn_lock_zzx.setEnabled(true);
                    return;
                }
                if ((lockerstatus.equals("00") && (op == CLOSE_LOCK)) || (lockerstatus.equals("01") && (op == OPEN_LOCK))) {
                    if ((lockerstatus.equals("00") && (op == CLOSE_LOCK))) {
                        new Thread() {
                            public void run() {
                                // 闭锁操作
                                Message msg = handler.obtainMessage();
                                String lockResult = "已处于闭锁状态";
                                Log.e(TAG, "lockResult=====" + lockResult);
                                msg.obj = lockResult;
                                msg.what = OPERATE_UNLOCK;
                                Log.e(TAG, "已处于闭锁状态！！！！！！！！！！！！！！！" + selenumber);
                                handler.sendMessage(msg);
                            }

                            ;
                        }.start();
                    } else if ((lockerstatus.equals("01") && (op == OPEN_LOCK))) {
                        new Thread() {
                            public void run() {
                                // 闭锁操作
                                Message msg = handler.obtainMessage();
                                String lockResult = "已处于开锁状态";
                                Log.e(TAG, "lockResult=====" + lockResult);
                                msg.obj = lockResult;
                                msg.what = OPERATE_LOCK;
                                Log.e(TAG, "已处于开锁状态！！！！！！！！！！！！！！！" + selenumber);
                                handler.sendMessage(msg);
                            }

                            ;
                        }.start();
                    }
//                    showBigToast(lockerstatus.equals("00") ? "锁已上锁" : "锁已开锁", 100);
                    return;
                }
            } else {

                return;
            }
        } else {
            Log.e(TAG, "manageLock锁未加电!!!!!!!!!!!!");
            showBigToast("请检查电源并重试", 300);
            return;
        }

        // 锁操作
        byte[] cmdParm = new byte[16];
        cmdParm[0] = (byte) (op == OPEN_LOCK ? 0x01 : 0x02);
        cmdParm[1] = 0x00;
        System.arraycopy(operator.getBytes(), 0, cmdParm, 2, operator.getBytes().length);
        byte[] randombytes = Util.hexStr2Bytes(random);
        for (int i = 0; i < 16; i++)
            cmdParm[i] = (byte) (cmdParm[i] ^ randombytes[i]);
        do {
            rfidDevice.LockOperation(3, cmdParm);
            replynum = receivelist.getElementNum();
            reply = receivelist.getFinishElement();
            count++;
            if (count == GlobalConstant.TRY_TICK)
                break;
        } while (!(reply.length > 21 && reply[2] == 0x49 && reply[20] == 0x00));
        if (count == GlobalConstant.TRY_TICK) {
            Log.e(TAG, "发送指令失败作!!!!!!!!!!!!" + reply.length + reply[2] + reply[20]);
            showBigToast("发送指令失败", 300);
            lockstate = true;
            return;
        }

        count = 0;
        do {
            rfidDevice.readUserData(0, 32);
            reply = receivelist.getFinishElement();
            count++;
            if (count == GlobalConstant.TRY_TICK)
                break;
        } while (!(reply.length > 3 && reply[2] == 0x39));
        if (count < GlobalConstant.TRY_TICK) {
            replyString = rfidDevice.getResult(reply);
            result = replyString.substring(10, 12);
            if (result.equals("00")) {

//                showBigToast(op == OPEN_LOCK ? "开锁成功" : "上锁成功", 500);
                Log.e(TAG, "开锁成功" + "上锁成功" + "op========op" + op);
                if (op == 0) {///发送闭锁成功锁成功上锁成功op========op1

                    new Thread() {
                        public void run() {
                            // 闭锁操作
                            Message msg = handler.obtainMessage();
                            String lockResult = "闭锁成功";
                            Log.e(TAG, "lockResult=====" + lockResult);
                            msg.obj = lockResult;
                            msg.what = OPERATE_UNLOCK;
                            handler.sendMessage(msg);
                        }

                        ;
                    }.start();
                } else if (op == 1) {
                    new Thread() {
                        public void run() {
                            // 闭锁操作
                            Message msg = handler.obtainMessage();
                            String lockResult = "开锁成功";
                            Log.e(TAG, "lockResult=====" + lockResult);
                            msg.obj = lockResult;
                            msg.what = OPERATE_LOCK;
                            handler.sendMessage(msg);
                        }

                        ;
                    }.start();
                }
                return;
            } else {
//                    showBigToast(op == OPEN_LOCK ? "开锁失败" : "上锁失败", 500);
                return;
            }
        } else {
            showBigToast("请查看锁的电源:", 300);
            rfidDevice.closeRFID();
            return;
        }


    }
/**
 *
 * 子线程开锁没实现
 */
    /////////////////////////////////////////////////////////////////////////////
//    private void manageLockNoDeal(int op) {
//        Log.e(TAG, "manageLock" + "op的值" + op);
//        int count = 0;
//        int replynum = 0;
//        String replyString = "";
//        String result = null;
//        String lockerstatus = null;
//        String linkerstatus = null;
//        String initialstatus = null;
//        String random = null;
//        manageButton(false);
//        int testcount = 0;
//        testcount = testcount + 1;
//        receivelist.removeAllElement();
//        byte[] cmd = op == 1 ? Util.hexStr2Bytes("0100") : Util.hexStr2Bytes("0200");
//        byte[] reply = null;
//        rfidDevice.selectMode();
//        reply = receivelist.getFinishElement();
//        count = 0;
//        do {
//            rfidDevice.selectEPC(selenumber);
//            replynum = receivelist.getElementNum();
//            count++;
//        } while (replynum == 0 && count < GlobalConstant.TRY_TICK);
//
//        if (count == GlobalConstant.TRY_TICK) {
//
//            showBigToast("没找到上电的锁请对准箱子电池位置", 100);
//            btn_unLock_zzx.setEnabled(true);
//            btn_lock_zzx.setEnabled(true);
//            Log.e(TAG, "无法选择对应的锁!!!!!!!");
//            return;
//        }
//        reply = receivelist.getFinishElement();
//        replyString = Util.byte2HexStr(reply);
//        // 获取锁的信息
//        count = 0;
//        do {
//            rfidDevice.LockOperation(1, null);
//            replynum = receivelist.getElementNum();
//            reply = receivelist.getFinishElement();
//            Log.e(TAG, "Locknumtest===" + selenumber);
//            Log.e(TAG, "reply===" + reply);
//            count++;
//            if (count == GlobalConstant.TRY_TICK)
//                break;
//        } while (!(reply.length > 21 && reply[2] == 0x49 && reply[20] == 0x00));
//        if (count == GlobalConstant.TRY_TICK) {
//            btn_unLock_zzx.setEnabled(true);
//            btn_lock_zzx.setEnabled(true);
//            showBigToast("锁接收信息异常请重试", 100);
//            btn_unLock_zzx.setEnabled(true);
//            btn_lock_zzx.setEnabled(true);
//            Log.e(TAG, "发送指令失败!!!!!!!!!!!!" + count);
//            return;
//        }
//        count = 0;
//        do {
//            rfidDevice.readUserData(0, 48);
//            reply = receivelist.getFinishElement();
//            count++;
//            if (count == GlobalConstant.TRY_TICK)
//                break;
//        } while (!(reply.length > 3 && reply[2] == 0x39));
//        if (count < GlobalConstant.TRY_TICK) {
//            replyString = rfidDevice.getResult(reply);
//            result = replyString.substring(8, 10);
//            lockerstatus = replyString.substring(34, 36);
//            linkerstatus = replyString.substring(36, 38);
//            initialstatus = replyString.substring(38, 40);
//            random = replyString.substring(40, 72);
//            if (!(linkerstatus.equals("00") || linkerstatus.equals("01") || linkerstatus.equals("FF"))) {
//                showBigToast("请检查箱是否盖好", 300);
//                Log.e(TAG, "链状态查询异常!!!!!!!!!!!!" + linkerstatus);//7F 127
//                btn_unLock_zzx.setEnabled(true);
//                btn_lock_zzx.setEnabled(true);
//                return;
//            }
//            if (!(initialstatus.equals("00") || initialstatus.equals("01"))) {
//                Log.e(TAG, "初始化查询异常!!!!!!!!!!!!" + initialstatus);
//                showBigToast("未查到锁请对准电池位置并重试", 100);
//                btn_unLock_zzx.setEnabled(true);
//                btn_lock_zzx.setEnabled(true);
//                return;
//            }
//            if (!(lockerstatus.equals("00") || lockerstatus.equals("01") || lockerstatus.equals("FF"))) {
//                showBigToast("请对准电池位置", 100);
//                btn_unLock_zzx.setEnabled(true);
//                btn_lock_zzx.setEnabled(true);
//                Log.e(TAG, "锁舌查询异常!!!!!!!!!!!!" + lockerstatus);
//                return;
//            }
//            o = o + 1;
//            Log.e(TAG, "测试mangerlock  走几次" + o);
//            if (result.equals("00")) {
//                if (linkerstatus.equals("01") || linkerstatus.equals("FF")) {
//                    Log.e(TAG, "获取锁状态失败!!!!!!!!!!!!");
//                    showBigToast(linkerstatus.equals("01") ? "拉链不就位" : "拉链状态异常", Toast.LENGTH_SHORT);
//                    btn_unLock_zzx.setEnabled(true);
//                    btn_lock_zzx.setEnabled(true);
//                    return;
//                }
//                if (initialstatus.equals("01")) {
//                    showBigToast("锁具未初始化请重试", Toast.LENGTH_SHORT);
//                    Log.e(TAG, "获取锁状态失败!!!!!!!!!!!!" + initialstatus);
//                    btn_unLock_zzx.setEnabled(true);
//                    btn_lock_zzx.setEnabled(true);
//                    return;
//                }
//                if ((lockerstatus.equals("00") && (op == CLOSE_LOCK)) || (lockerstatus.equals("01") && (op == OPEN_LOCK))) {
//                    if ((lockerstatus.equals("00") && (op == CLOSE_LOCK))) {
//                        new Thread() {
//                            public void run() {
//                                // 闭锁操作
//                                Message msg = handler.obtainMessage();
//                                String lockResult = "已处于闭锁状态";
//                                Log.e(TAG, "lockResult=====" + lockResult);
//                                msg.obj = lockResult;
//                                msg.what = OPERATE_UNLOCK;
//                                Log.e(TAG, "已处于闭锁状态！！！！！！！！！！！！！！！" + selenumber);
//                                handler.sendMessage(msg);
//                            }
//
//                            ;
//                        }.start();
//                    } else if ((lockerstatus.equals("01") && (op == OPEN_LOCK))) {
//                        new Thread() {
//                            public void run() {
//                                // 闭锁操作
//                                Message msg = handler.obtainMessage();
//                                String lockResult = "已处于开锁状态";
//                                Log.e(TAG, "lockResult=====" + lockResult);
//                                msg.obj = lockResult;
//                                msg.what = OPERATE_LOCK;
//                                Log.e(TAG, "已处于开锁状态！！！！！！！！！！！！！！！" + selenumber);
//                                handler.sendMessage(msg);
//                            }
//
//                            ;
//                        }.start();
//                    }
////                    showBigToast(lockerstatus.equals("00") ? "锁已上锁" : "锁已开锁", 100);
//                    return;
//                }
//            }
//
//        }
//
//    }

    /***
     * 确定开那把锁时需要传的值方法
     * @return
     */
    public String setSendLockNumber() {


        try {
            if (locknum == (null) || !locknum.contains(selenumber)) {
                String a = Guolv(selenumber);
                Log.e(TAG, "aaaaaa===" + a + locknum.size());
                locknum.add(selenumber);
                return a;

            } else {
                Log.e(TAG, "不做操作");
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "异常" + e);
        }
        return null;
    }


    /**
     * 把对密码锁的操作保存到数据库
     *
     * @param info
     */
    private void saveOperateDecodedLockLog(final String info) {
        new Thread() {
            public void run() {
                OperateLog operateLog = new OperateLog();
                operateLog.setOperateType(OperateLog.OPERATE_LOG);
                operateLog.setUserID(App.userZhanghao);
                operateLog.setCorpId(App.user.getOrganizationId());
                operateLog.setOperateContent(info);
                operateLog.setOperateTime(new Timestamp(System.currentTimeMillis()));
                operateLog.setState(OperateLog.SUCCESS);
                try {
                    UpServer.saveOperateLog(operateLog);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();
    }

    /**
     * 每次操作密码锁后，根据返回结果修改密码锁的状态
     * strBox 和zzxt   的状态
     *
     * @param result
     */
    private void changeLockState(String result) {
        if ("开锁成功".equals(result) || "已处于开锁状态".equals(result)) {
            Log.e(TAG, "strbox" + selenumber);
            this.lockStateMap.put(selenumber, "unlock");
        } else if ("闭锁成功".equals(result) || "已处于闭锁状态".equals(result)) {
            this.lockStateMap.put(selenumber, "lock");
        }
    }

    /**
     * 检测扫描到的周装箱是否全部处于闭锁状态
     *
     * @return true:扫描到的周转箱已经全部上锁，false：有部分周转箱没有上锁
     */
    public boolean isAllLocked() {
        String gulv;
        Log.e(TAG, "this.this.lockStateMap" + this.lockStateMap);
        if (this.lockStateMap.size() == 0) {
            showBigToast("请给周装箱上锁", Toast.LENGTH_SHORT);
            return false;
        } else {
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : this.lockStateMap.entrySet()) {
                if (!"lock".equals(entry.getValue())) {
                    sb.append(entry.getKey() + ", ");
                }
            }
            if (sb.length() == 0) {
                return true;
            } else {
                Log.e(TAG, sb.substring(0, sb.lastIndexOf(",")).toString());
                gulv = Guolv(sb.substring(0, sb.lastIndexOf(",")).toString());
//                showBigToast("请给周转箱:" + sb.substring(0, sb.lastIndexOf(",")).toString() + " 上锁！", Toast.LENGTH_SHORT);
                showBigToast("请给周转箱:" + gulv + " 上锁！", Toast.LENGTH_SHORT);
                return false;
            }
        }
    }

    /**
     * 检测扫描到的周装箱是否全部处于开锁状态
     *
     * @return true:扫描到的周转箱已经全部开锁，false：有部分周转箱没有开锁
     */


    public boolean isAllUnlocked() {
        String gv;
        if (this.lockStateMap.size() == 0) {
            showBigToast("请给周装箱开锁！", 500);
            return false;
        } else {
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : this.lockStateMap.entrySet()) {
                if (!"unlock".equals(entry.getValue())) {
                    sb.append(entry.getKey() + ", ");
                    mapstatesize();
                }
            }
            if (sb.length() == 0) {
                return true;
            } else {
                gv = Guolv(sb.substring(0, sb.lastIndexOf(",")).toString());
                showBigToast("请给周转箱:" + gv + " 开锁", Toast.LENGTH_SHORT);
                return false;
            }
        }
    }

    public Map<String, String> mapstatesize() {
        for (Map.Entry<String, String> entry : this.lockStateMap.entrySet()) {
            locknumMapstateb.put(entry.getKey(), "unlock");
        }
        return locknumMapstateb;
    }

    /**
     * 自定义 toast， 增大字体
     *
     * @param info     提示信息
     * @param duration 显示时间，0：短时间，1：长时间
     */
    public void showBigToast(String info, int duration) {
//        Toast toast = new Toast(kf.getActivity());

        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 50);
        TextView tv = new TextView(context);
        tv.setBackgroundResource(R.drawable.bg_toast);
        tv.setGravity(Gravity.CENTER);
        tv.setPadding(25, 5, 25, 5);
        tv.setTextColor(Color.WHITE);
        tv.setText(info);
        tv.setTextSize(30);
        toast.setView(tv);
        toast.setDuration(duration);
        toast.show();
    }

    /***
     * 设置对锁的监听
     */
    private void createListener() {
        listener = new RFIDDevice.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
                // TODO Auto-generated method stub
                // 如果接收序列为空直接将数据加入到接收序列中,
                byte[] tempbuffer = null;

                if (receivelist.getElementNum() != 0 && !receivelist.getLastElementStatus()) {
                    byte[] lastbuf = receivelist.getLastElement();
                    tempbuffer = new byte[lastbuf.length + size];
                    System.arraycopy(lastbuf, 0, tempbuffer, 0, lastbuf.length);
                    System.arraycopy(buffer, 0, tempbuffer, lastbuf.length, size);
                    receivelist.removeLastElement();
                } else {
                    tempbuffer = new byte[size];
                    System.arraycopy(buffer, 0, tempbuffer, 0, size);
                }
                // 按照接收buffer的最后一字节判断是否接收完毕
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length < 5) || (tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && (tempbuffer[4] + 7) > tempbuffer.length)) {
                    receivelist.addElement(tempbuffer, false);
                    Log.e("KSS方法", "Decode方法的第一个分支猜测");
                }
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && ((int) tempbuffer[4] + 7) <= tempbuffer.length)) {
                    Log.e("KSS方法", "Decode方法的第一个分支猜测");
                    int bytelen = tempbuffer[4] + 7;
                    byte[] newbyte = new byte[bytelen];
                    System.arraycopy(tempbuffer, 0, newbyte, 0, bytelen);
                    receivelist.addElement(newbyte, true);
                    if ((tempbuffer.length - bytelen) > 0) {
                        newbyte = new byte[tempbuffer.length - bytelen];
                        System.arraycopy(tempbuffer, bytelen, newbyte, 0, tempbuffer.length - bytelen);
                        receivelist.addElement(newbyte, false);
                    }
                }
            }
        };
        rfidDevice.setOnDataReceiveListener(listener);
    }

    private void manageButton(boolean enable) {
    }

    /**
     * 过滤器
     *
     * @param str
     * @return
     */
    public String Guolv(String str) {

        try {
            if (str.equals("") || null == str) {
                showBigToast("请检查锁的状态", 100);
                return " ";
            } else {
                Log.e(TAG, "str111111====" + str);
                String box = CaseString.getBoxNum(str);//这个方法以后自己去修改
                if (box.length() < 2) {
                    return "";
                }
                String stx = box.substring(box.length() - 2, box.length());
                if ("ZZ".equals(stx)) {
                    return box;
                } else {
                    return "箱子规格不正确";
                }
                //	return box;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 设置监听 和RFID 的实例化
     * <p>
     * 曾为public
     */
    private void listener() {
        createListener();
        Log.e(TAG, "kssrfragemtn ：initContexnt");
        rfidDevice.setOnDataReceiveListener(listener);
    }


    public void oPenClose() {
        searchLock();
    }

    /****
     * 开那把锁
     * @return
     */
    public String selectedZzxNum() {

        try {
            if (!selectedZzxNum.equals("")) {
                String select = selectedZzxNum;
                return select;
            } else {
                showBigToast("请选择周转箱号", 100);
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    /***
     * 添加到周转箱集合将箱子
     * @return
     */
    public List zList() {
        if (Zlist.size() > 0 && !Zlist.contains(zzxt)) {
            return Zlist;
        }
        return null;
    }

}




















